package com.liuguang.common.utils;


import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.security.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: RSAUtils
 * @Description： 自定义RSAUtils
 * @Author: wanghr
 * Date: 5:47 PM 2020/9/11
 * Version: 1.0
 */
public class RSAUtils {
    private static final String RSA_KEY_ALGORITHM = "RSA";

    private static final int KEY_SIZE = 1024;

    /**
     *  获取密钥对，
     * @params: null
     * @return: java.utils.Map<java.lang.String,java.lang.Object>
     */
    public static Map<String, Object> getKeys() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();
        HashMap<String, Object> map = new HashMap<>();
        map.put("privateKey", privateKey);
        map.put("publicKey", publicKey);
        return map;
    }

    public static String encryptByPublicKey(String data,PublicKey publicKey) {
        if (StringUtils.isEmpty(data) || ObjectUtils.isEmpty(publicKey)) {
            throw new NullPointerException("参数不能为null");
        }
//        Cipher.getInstance()
        return null ;
    }

    //测试加密、解密
    public static void main(String[] args) {
        try {
            RSA rsa0 = SecureUtil.rsa();
            String privateKeyBase64 = rsa0.getPrivateKeyBase64();
            String publicKeyBase64 = rsa0.getPublicKeyBase64();

            RSA rsa = SecureUtil.rsa(privateKeyBase64, publicKeyBase64);
            byte[] encrypt = rsa.encrypt("wo王", KeyType.PublicKey);
            String passwordEncode = Base64.encode(encrypt);

            System.out.println(passwordEncode.length());
            System.out.println("passwordEncode = " + passwordEncode);



            RSA rsa1 = SecureUtil.rsa(privateKeyBase64, publicKeyBase64);
            byte[] decode = Base64.decode(passwordEncode);

            byte[] decrypt = rsa1.decrypt(decode, KeyType.PrivateKey);
            String s = new String(decrypt);
            System.out.println("s = " + s);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
